import { Inject } from '@angular/core';

import { SERVER_URL } from '../constant';
import { HttpClient } from '@angular/common/http';
import AbstractService from './abstract.service';
import AbstractModel from '../model/abstract.model';
import { TokenStorageService } from './storage.service';

enum URL_TYPE { 
    GET = 1,
    FIND = 2,
    ADD = 3,
    UPDATE = 4,
    DELETE = 5
}

export default class BaseService<T extends AbstractModel> extends AbstractService<T> { 
    public resourceUrl: string;

    constructor(public $class, public resourceName: string, public tokenStorage: TokenStorageService, public http?: HttpClient) { 
        super($class, tokenStorage);
        this.resourceUrl = `${SERVER_URL}/${this.resourceName}`;
    }

    public appendToken(options: any) { 
        let token = this.tokenStorage.getToken();
        if (!options) { 
            options = {};
        }
        if (!options.headers) { 
            options.headers = {};
        }
        options.headers.token = token;
        return options;
    }

    $get(id: number, options) { 
        options = this.appendToken(options);
        return this.http.get(`${this.resourceUrl}/${id}`, options);
    }

    $add(obj: T, options: any) { 
        options = this.appendToken(options);
        return this.http.post(`${this.resourceUrl}`, obj, options);
    }

    $update(obj: T, options: any) { 
        options = this.appendToken(options);
        return this.http.put(`${this.resourceUrl}/${obj.id}`, obj, options);
    }
    $find(where, options) { 
        options = this.appendToken(options);
        options.params = where;
        return this.http.get(`${this.resourceUrl}`, options);
    }
    
    $delete(id: number, options) { 
        options = this.appendToken(options);
        return this.http.delete(`${this.resourceUrl}/${id}`, options);
    }
}